/**
 * 
 */
package helper;

import indexer.*;
import java.sql.*;

/**
 * @author Pascal de Vink
 * @version 0.2
 */
public class MysqlDatabase {

	static private Statement stmt;
	
	public MysqlDatabase()
	{
		openDatabase();
	}
	
	private void openDatabase()
	{
		if (MysqlDatabase.stmt == null) {
			try {	
			    //Register the JDBC driver for MySQL.
			    Class.forName("com.mysql.jdbc.Driver");
	
			    //Define URL of database server for
			    // database named mysql on the localhost
			    // with the default port number 3306.
			    String url = Dispatcher.SQLURL;
	
			    //Get a connection to the database for a
			    // user named root with a blank password.
			    // This user is the default administrator
			    // having full privileges to do anything.
			    Connection con = DriverManager.getConnection(url,Dispatcher.SQLUSER, Dispatcher.SQLPASS);
	
			    //Display URL and connection information
			    //System.out.println("URL: " + url);
			    //System.out.println("Connection: " + con);
	
			    //Get a Statement object
			    MysqlDatabase.stmt = con.createStatement();
			} catch (Exception e) {
				 e.printStackTrace();
			}
		}
	}
	
	public ResultSet select(String command) throws SQLException
	{
		return MysqlDatabase.stmt.executeQuery(command);
	}
	
	public void insert(String command) throws SQLException
	{
		MysqlDatabase.stmt.executeUpdate(command);
	}
	
	public void empty(String table) throws SQLException
	{
		MysqlDatabase.stmt.execute("TRUNCATE TABLE `"+table+"`");
	}
	
	public void closeDatabase()
	{
		if (MysqlDatabase.stmt != null)
		{
			try {
				MysqlDatabase.stmt.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
}
